<?php

namespace App;

use Illuminate\Support\Facades\DB;

class SpecGoodsPrice extends Base
{
    protected $fillable = ['goods_id', 'key', 'value', 'price', 'stock'];
    protected $hidden = ['created_at', 'updated_at'];

    public function setPriceAttribute($value)
    {
        $this->attributes['price'] = floatval($value);
    }
    public function setStockAttribute($value)
    {
        $this->attributes['stock'] = intval($value) != '' ? intval($value) : 0;
    }

    // 查询商品的所有 规格
    public static function ByGoods ($goodsId)
    {
        // 查询商品的所有 规格项id
        $goodsItems = self::where('goods_id', $goodsId)->value(DB::raw("GROUP_CONCAT(`key` SEPARATOR '_')"));
        $goodsItems = array_values(array_unique(explode('_', $goodsItems)));
        // 查询该商品拥有的 规格
        $specs = Spec::whereHas('items', function ($query) use ($goodsItems)  {
            return $query->whereIn('id', $goodsItems);
        })->get();

        // 查询商品的所有 规格项
        $items = SpecItem::whereIn('id', $goodsItems)->get();
        $arr = [];
        foreach($specs as &$spec) {
            $specImtes = [];
            $spec->checked = null;  // 用户选择的规格
            foreach($items as $item) {
                if ($item->spec_id == $spec->id) {
                    $item->image = SpecGoodsImage::where('goods_id', $goodsId)->where('spec_item_id', $item->id)->value('thumb');
                    $specImtes[] = $item;
                    $spec->items = $specImtes;
                }
            }
        }
        return $specs;
    }
}
